package com.gpj.learn.netty.buffer.simple;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.security.SecureRandom;

/**
 * @className BufferUtil
 * @description
 *   工具类，可以忽略不计
 * @author GPJ
 * @date 2020/2/12 12:00
 * @version 1.0
 **/
@Slf4j
public class BufferLogUtil {
    public static <T extends Buffer> void bufferInfoLog(T buffer){
        log.info("buffer信息 --> {position:{}, limit:{}, capacity:{}}", buffer.position(), buffer.limit(), buffer.capacity());
    }

    /*public static <T extends Buffer> void bufferDataLog(T buffer){
        log.info("---------------------- buffer内容输出 start ---------------------------");
        try {
            while (buffer.hasRemaining()) {
                final Method get = buffer.getClass().getMethod("get");
                final Object data = get.invoke(buffer);
                log.info("buffer写入值为 --> {{}}", data);
            }
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        log.info("---------------------- buffer内容输出 end ---------------------------");
    }*/

    public static <T extends Buffer> void bufferDatasLog(T buffer){
        try {
            final Method get = buffer.getClass().getMethod("array");
            final Object datas = get.invoke(buffer);
            if(buffer instanceof ByteBuffer){
                log.info("buffer写入值为 --> {{}}", new String((byte[]) datas));
            }else{
                log.info("buffer写入值为 --> {{}}", datas);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static IntBuffer generateIntBufferWithDatas(int capacity){
        final IntBuffer buffer = IntBuffer.allocate(capacity);
        while (buffer.hasRemaining()){
            buffer.put(new SecureRandom().nextInt());
        }
        return buffer;
    }
}
